package org.linlinjava.litemall.db.service;

import com.github.pagehelper.PageHelper;
import org.linlinjava.litemall.db.dao.LitemallShopMapper;
import org.linlinjava.litemall.db.domain.LitemallShop;
import org.linlinjava.litemall.db.domain.LitemallShop.Column;
import org.linlinjava.litemall.db.domain.LitemallShopExample;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class LitemallShopService {
    @Resource
    private LitemallShopMapper shopMapper;
    private Column[] columns = new Column[]{Column.id, Column.name, Column.shopLogo, Column.simpleDesc, Column.address};

    public List<LitemallShop> query(Integer page, Integer limit, String sort, String order) {
        LitemallShopExample example = new LitemallShopExample();
//        example.or().andDeletedEqualTo(false);
        if (!StringUtils.isEmpty(sort) && !StringUtils.isEmpty(order)) {
            example.setOrderByClause(sort + " " + order);
        }
        PageHelper.startPage(page, limit);
        return shopMapper.selectByExampleSelective(example, columns);
    }

    public List<LitemallShop> query(Integer page, Integer limit) {
        return query(page, limit, null, null);
    }

    public LitemallShop findById(Integer id) {
        return shopMapper.selectByPrimaryKey(id);
    }

    public List<LitemallShop> querySelective(String id, String name, Integer page, Integer size, String sort, String order) {
        LitemallShopExample example = new LitemallShopExample();
        LitemallShopExample.Criteria criteria = example.createCriteria();

        if (!StringUtils.isEmpty(id)) {
            criteria.andIdEqualTo(Integer.valueOf(id));
        }
        if (!StringUtils.isEmpty(name)) {
            criteria.andNameLike("%" + name + "%");
        }

        if (!StringUtils.isEmpty(sort) && !StringUtils.isEmpty(order)) {
            example.setOrderByClause(sort + " " + order);
        }

        PageHelper.startPage(page, size);
        return shopMapper.selectByExample(example);
    }

    public int updateById(LitemallShop shop) {
        return shopMapper.updateByPrimaryKeySelective(shop);
    }

    public void deleteById(Integer id) {
        shopMapper.deleteByPrimaryKey(id);
    }

    public void add(LitemallShop shop) {
        shop.setAddTime(LocalDateTime.now());
        shopMapper.insertSelective(shop);
    }

    public List<LitemallShop> all() {
        LitemallShopExample example = new LitemallShopExample();
//        example.or().andDeletedEqualTo(false);
        return shopMapper.selectByExample(example);
    }
}
